import { get } from "./Axios";

/**
 * 获取城市列表数据
 * @returns
 */
export const getCityListUtil = async (curCity) => {
  return new Promise(async (res, reject) => {
    const cityList = {};

    const list = await get("/area/city?level=1");

    list.data.body.forEach((element) => {
      const first = element.short.substr(0, 1);
      if (cityList[first]) {
        cityList[first].push(element);
      } else {
        cityList[first] = [element];
      }
    });

    const cityIndex = Object.keys(cityList).sort();
    cityIndex.unshift("hot");
    cityIndex.unshift("cur");
    const hotData = await get("/area/hot");
    cityList["hot"] = [];
    cityList["cur"] = [];
    hotData.data.body.forEach((one) => {
      cityList["hot"].push(one);
    });

    const data = JSON.parse(localStorage.getItem("cache_city_msg"));
    if (!data) {
      const curCity = new window.BMapGL.LocalCity();
      curCity.get(
        (result) => {
          get("/area/info", {
            name: result.name,
          }).then((data) => {
            result.value = data.data.body.value;
            result.label = data.data.body.label;

            cityList["cur"].push(result);
            res({ cityList, cityIndex });
          });
        },
        (err) => {
          reject(err);
        }
      );
    } else {
      cityList["cur"].push(data);
      res({ cityList, cityIndex });
    }
  });
};
